package com.tanger.common.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Descripton: JSON工具类
 * @Author: Hchenbin
 * @Date:2022/6/23 15:35
 */
public final class JSON {
    private static final Logger LOG = LoggerFactory.getLogger(JSON.class);
    private static final ObjectMapper MAPPER = objectMapper();

    public static <T> T parse(String content, Class<T> tClass){
        try {
            return MAPPER.readValue(content, tClass);
        } catch (JsonProcessingException e) {
            LOG.error("json parse exception", e);
            return null;
        }
    }

    public static String stringify(Object value) {
        try {
            return MAPPER.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            LOG.error("json stringify exception", e);
            return null;
        }
    }

    private static ObjectMapper objectMapper() {
        ObjectMapper result = new ObjectMapper();
        //序列化的时候序列对象的所有属性
        result.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //反序列化的时候如果多了其他属性,不抛出异常
        result.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //如果是空对象的时候,不抛异常
        result.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        return result;
    }

    private JSON() {
    }
}
